package com.github.iot.activity;

import android.os.Bundle;
import android.view.View;

import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.DialogFragment;

import com.github.iot.R;
import com.github.iot.adapter.ShowcaseAdapter;
import com.github.iot.dao.CommonDaoUtils;
import com.github.iot.dao.DaoUtilsStore;
import com.github.iot.entity.Showcase;
import com.github.iot.entity.Showroom;
import com.github.iot.utils.ActivityUtils;
import com.github.iot.utils.BarUtils;
import com.github.iot.utils.FastJsonUtils;
import com.github.iot.utils.ToastUtils;
import com.github.iot.view.LineGridView;
import com.github.iot.view.RxTitle;
import com.github.iot.view.dialogs.fragment.SimpleDialogFragment;
import com.github.iot.view.dialogs.iface.ISimpleDialogListener;
import com.github.iot.view.loaddatalayout.LoadDataLayout;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;

/**
 * 展厅Activity
 *
 * @Author: 梁声洪
 * @Date: 2019/12/11 9:14
 * @Version: v1.0.0
 */
public class ShowroomActivity extends AppCompatActivity implements ISimpleDialogListener {

    private static final int REQUEST_OPTION_DIALOG = 1;
    private static final int REQUEST_DELETE_DIALOG = 2;

    @BindView(R.id.rx_title)
    RxTitle mTitle;

    @BindView(R.id.loadDataLayout)
    LoadDataLayout mLoadDataLayout;

    @BindView(R.id.gv_showcase)
    LineGridView mGridView;

    private ShowcaseAdapter mAdapter;
    private Showroom showroom;
    private DialogFragment mDialog1;
    private DialogFragment mDialog2;
    private boolean flag = true;
    private List<Showcase> mDatas = new ArrayList<>();
    private static CommonDaoUtils<Showroom> showroomDaoUtils = DaoUtilsStore.getInstance().getShowroomDaoUtils();
    private static CommonDaoUtils<Showcase> showcaseDaoUtils = DaoUtilsStore.getInstance().getShowcaseDaoUtils();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        BarUtils.setStatusBarColor(this, R.color.colorPrimaryDark);
        setContentView(R.layout.activity_showroom);

        ButterKnife.bind(this);
        String str = getIntent().getStringExtra("showroom");
        showroom = FastJsonUtils.strToBean(str, Showroom.class);

        initView();
        initData();
    }

    private void initView() {
        mTitle.setLeftFinish(this);
        mTitle.setTitle(showroom.getTitle());

        mGridView.setFocusable(false);
        mGridView.setOnItemClickListener((parent, view, position, id) -> {
            if (flag) {
                flag = false;
                Showcase showcase = mDatas.get(position);
                Bundle bundle = new Bundle();
                bundle.putString("showcase", FastJsonUtils.obj2JsonStr(showcase));
                ActivityUtils.skipActivity(ShowroomActivity.this, ShowcaseActivity.class, bundle);
            }
        });

        mGridView.setOnItemLongClickListener((parent, view, position, id) -> {
            Showcase showcase = mDatas.get(position);
            mDialog1 = SimpleDialogFragment.createBuilder(ShowroomActivity.this, getSupportFragmentManager())
                    .setTitle("系统提示")
                    .setMessage("请选择您操作步骤")
                    .setCancelable(false)
                    .setPositiveButtonText("取消")
                    .setNegativeButtonText("修改")
                    .setNeutralButtonText("删除")
                    .setTag(FastJsonUtils.obj2JsonStr(showcase))
                    .setRequestCode(REQUEST_OPTION_DIALOG)
                    .show();
            return true;
        });

        mLoadDataLayout.getEmptyView().setOnClickListener(v -> {
            Bundle bundle = new Bundle();
            bundle.putString("showroom", FastJsonUtils.obj2JsonStr(showroom));
            bundle.putInt("sort", mDatas.size());
            ActivityUtils.skipActivity(ShowroomActivity.this, AddShowcaseActivity.class, bundle);
        });
    }

    private void initData() {
        flag = true;
        mLoadDataLayout.setStatus(LoadDataLayout.LOADING);
        Observable.timer(100, TimeUnit.MILLISECONDS)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(t -> getData());
    }

    private void getData() {
        String sql = "where SHOWROOM_ID = ? order by _id ASC";
        String[] conditions = new String[]{String.valueOf(showroom.getId())};
        mDatas = showcaseDaoUtils.queryByNativeSql(sql, conditions);
        if (mDatas.size() > 0) {
            mLoadDataLayout.setStatus(LoadDataLayout.SUCCESS);
            mAdapter = new ShowcaseAdapter(ShowroomActivity.this, mDatas);
            mGridView.setAdapter(mAdapter);
        } else {
            mLoadDataLayout.setStatus(LoadDataLayout.EMPTY);
        }
    }

    /**
     * 删除展厅信息
     *
     * @param showcase
     */
    private void deleteShowcase(Showcase showcase) {
        boolean flag = showcaseDaoUtils.delete(showcase);
        if (flag) {
            showroom.setNum(showroom.getNum() - 1);
            showroomDaoUtils.update(showroom);

            initData();
            ToastUtils.success("操作成功");
        } else {
            ToastUtils.error("操作失败");
        }
    }

    @OnClick({R.id.fab})
    public void onViewClicked(View view) {
        if (view.getId() == R.id.fab) {
            Bundle bundle = new Bundle();
            bundle.putString("showroom", FastJsonUtils.obj2JsonStr(showroom));
            bundle.putInt("sort", mDatas.size());
            ActivityUtils.skipActivity(ShowroomActivity.this, AddShowcaseActivity.class, bundle);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        initData();
    }

    @Override
    public void onNegativeButtonClicked(int requestCode) {
        // 修改
        if (requestCode == REQUEST_OPTION_DIALOG) {
            if (null != mDialog1) {
                String tag = mDialog1.getTag();
                if (null != tag) {
                    Bundle bundle = new Bundle();
                    bundle.putString("showcase", tag);
                    ActivityUtils.skipActivity(ShowroomActivity.this, UpdateShowcaseActivity.class, bundle);
                }
            }
        }
    }

    @Override
    public void onNeutralButtonClicked(int requestCode) {
        // 删除
        if (requestCode == REQUEST_OPTION_DIALOG) {
            if (null != mDialog1) {
                String tag = mDialog1.getTag();
                Showcase showcase = FastJsonUtils.strToBean(tag, Showcase.class);
                mDialog2 = SimpleDialogFragment.createBuilder(ShowroomActivity.this, getSupportFragmentManager())
                        .setTitle("系统提示")
                        .setMessage("您确定要删除[" + showcase.getName() + "]吗？")
                        .setCancelable(false)
                        .setTag(tag)
                        .setPositiveButtonText("确定")
                        .setNegativeButtonText("取消")
                        .setRequestCode(REQUEST_DELETE_DIALOG)
                        .show();
            }
        }
    }

    @Override
    public void onPositiveButtonClicked(int requestCode) {
        // 删除
        if (requestCode == REQUEST_DELETE_DIALOG) {
            if (null != mDialog2) {
                String tag = mDialog2.getTag();
                if (null != tag) {
                    Showcase showcase = FastJsonUtils.strToBean(tag, Showcase.class);
                    deleteShowcase(showcase);
                }
            }
        }
    }

}